<template>
	<view class="container">
		<!-- 全屏加载遮罩 -->
		<view class="loading-mask" v-if="isUploading">
			<view class="loading-content">
				<view class="loading-spinner"></view>
				<text class="loading-text">图片上传中...</text>
			</view>
		</view>
		
		<view class="form-section">
			<!-- 基本信息 -->
			<view class="section-title">基本信息</view>
			<view class="top-layout">
				<!-- 左侧图片 -->
				<view class="image-container">
					<text class="image-label">预览图<text class="required-mark">*</text></text>
					<view class="image-upload" @tap="chooseImage">
						<image v-if="product.preview_image_url" :src="product.preview_image_url" mode="aspectFill" class="preview-image"></image>
						<view v-else class="upload-placeholder">
							<text class="iconfont">+</text>
						</view>
					</view>
				</view>
				
				<!-- 右侧信息 -->
				<view class="info-container">
					<!-- 将类别和仓库放在同一行 -->
					<view class="form-row">
						<view class="form-item half-width horizontal">
							<text class="label-inline">类别<text class="required-mark">*</text></text>
							<view style="width: 10px;"></view>
							<picker @change="handleCategoryChange" :value="categories.indexOf(selectedCategory)" :range="categories">
								<view class="picker">{{selectedCategory || '请选择'}}</view>
							</picker>
						</view>

						<view class="form-item half-width horizontal">
							<text class="label-inline">仓库</text>
							<view style="width: 10px;"></view>
							<picker @change="handleWarehouseChange" :value="warehouses.indexOf(selectedWarehouse)" :range="warehouses" >
								<view class="picker">{{selectedWarehouse || '请选择'}}</view>
							</picker>
						</view>
					</view>
					<view style="height: 4px;"></view>
					<view class="form-item horizontal">
						<text class="label-inline">名称<text class="required-mark">*</text></text>
						<view style="width: 10px;"></view>
						<input type="text" v-model="product.name" placeholder="请输入商品名称" class="full-width-input" />
					</view>
					<view style="height: 4px;"></view>

					<view class="form-item horizontal" >
						<text class="label-inline">时间</text>
						<text class="required-mark">*</text>
						<view style="width: 10px;"></view>
						<uni-datetime-picker 
							type="date" 
							v-model="product.date" 
							@change="handleDateChange"
							format="yyyy-MM-dd"
							class="calendar-picker"
							:clear-icon="false"
							return-type="string"
						/>
					</view>
				</view>
			</view>
			
			<!-- 规格信息 -->
			<view class="section-title">规格信息</view>
			
			<!-- 整体长度 (列表) -->
			<view class="form-item">
				<text class="label">整体长度(毫米)</text>
				<view class="list-container">
					<view class="list-item" v-for="(item, index) in selectedLengthList" :key="index">
						<text class="item-text">{{item}}</text>
						<text class="delete-btn" @tap="deleteItem('lengthList', index)">×</text>
					</view>
					<view class="add-item-btn" @tap="showAddItemDialog('lengthList')">+</view>
				</view>
			</view>
			
			<!-- 佩戴直径 (列表) -->
			<view class="form-item">
				<text class="label">佩戴直径(毫米)</text>
				<view class="list-container">
					<view class="list-item" v-for="(item, index) in selectedDiameterList" :key="index">
						<text class="item-text">{{item}}</text>
						<text class="delete-btn" @tap="deleteItem('diameterList', index)">×</text>
					</view>
					<view class="add-item-btn" @tap="showAddItemDialog('diameterList')">+</view>
				</view>
			</view>
			
			<!-- 珍珠尺寸 (列表) -->
			<view class="form-item">
				<text class="label">珍珠尺寸(毫米)</text>
				<view class="list-container">
					<view class="list-item" v-for="(item, index) in selectedPearlSizeList" :key="index">
						<text class="item-text">{{item}}</text>
						<text class="delete-btn" @tap="deleteItem('pearlSizeList', index)">×</text>
					</view>
					<view class="add-item-btn" @tap="showAddItemDialog('pearlSizeList')">+</view>
				</view>
			</view>
			
			<!-- 珍珠颜色 (列表) -->
			<view class="form-item">
				<text class="label">珍珠颜色</text>
				<view class="list-container">
					<view class="list-item" v-for="(item, index) in selectedPearlColorList" :key="index">
						<text class="item-text">{{item}}</text>
						<text class="delete-btn" @tap="deleteItem('pearlColorList', index)">×</text>
					</view>
					<view class="add-item-btn" @tap="showAddItemDialog('pearlColorList')">+</view>
				</view>
			</view>
			
			<!-- 珍珠信息 -->
			<view class="section-title">珍珠信息</view>
			
			<view class="form-row">
				<view class="form-item half-width">
					<text class="label-inline">珍珠圆度</text>
					<view style="width: 10px;"></view>
					<picker @change="handlePearlRoundnessChange" :value="pearlRoundness.indexOf(selectedPearlRoundness)" :range="pearlRoundness">
						<view class="picker">{{selectedPearlRoundness || '请选择珍珠圆度'}}</view>
					</picker>
				</view>
				<view class="form-item half-width">
					<text class="label-inline">珍珠净度</text>
					<view style="width: 10px;"></view>
					<picker @change="handlePearlClarityChange" :value="pearlClarities.indexOf(selectedPearlClarity)" :range="pearlClarities">
						<view class="picker">{{selectedPearlClarity || '请选择珍珠净度'}}</view>
					</picker>
				</view>
			</view>
			
			<view class="form-row">
				<view class="form-item half-width">
					<text class="label-inline">珍珠材质</text>
					<view style="width: 10px;"></view>
					<picker @change="handlePearlMaterialChange" :value="pearlMaterials.indexOf(selectedPearlMaterial)" :range="pearlMaterials">
						<view class="picker">{{selectedPearlMaterial || '请选择珍珠材质'}}</view>
					</picker>
				</view>
				<view class="form-item half-width">
					<text class="label-inline">金属材质</text>
					<view style="width: 10px;"></view>
					<picker @change="handleMetalMaterialChange" :value="metalMaterials.indexOf(selectedMetalMaterial)" :range="metalMaterials">
						<view class="picker">{{selectedMetalMaterial || '请选择金属材质'}}</view>
					</picker>
				</view>
			</view>
			

			<view class="form-row">
				<view class="form-item half-width">
					<text class="label-inline">玉石材质</text>
					<input type="text" v-model="product.jadeMaterial" placeholder="请输入玉石材质" />
				</view>
				<view class="form-item half-width">
					<text class="label-inline">玉石尺寸</text>
					<view class="input-with-unit">
						<input type="text" v-model="product.jadeSize" placeholder="请输入玉石尺寸" />
						<text class="unit-label">mm</text>
					</view>
				</view>
			</view>

			<!-- 配件信息 -->
			<view class="section-title">配件信息</view>
			<view class="form-item">
				<input type="text" v-model="product.accessoryOthers" placeholder="请输入其他配件信息" />
			</view>
			
			<!-- 备注信息 -->
			<view class="section-title">备注信息</view>
			<view class="form-item">
				<textarea v-model="product.remark" placeholder="请输入备注信息" class="remark-input"></textarea>
			</view>
			
			<!-- 渠道信息 -->
			<view class="section-title">渠道信息</view>
			<view class="form-item">
				<view class="channel-list">
					<view class="channel-item" v-for="(channel, index) in product.channel" :key="index">
						<view class="channel-content">
							<text class="channel-name">{{channel.name}}</text>
							<text class="channel-link">{{channel.link}}</text>
						</view>
						<text class="delete-btn" @tap="deleteChannel(index)">×</text>
					</view>
					<view class="add-item-btn" @tap="showAddChannelDialog">+</view>
				</view>
			</view>
		</view>
		
		<!-- 底部按钮 -->
		<view class="bottom-bar">
			<view class="bottom-btn-container">
				<button class="back-btn" @tap="goBack">返回</button>
				<button class="next-btn" @tap="goToSkuPage">下一步</button>
			</view>
		</view>
		
		<!-- 添加项目弹窗 -->
		<uni-popup ref="addItemPopup" type="dialog">
			<uni-popup-dialog 
				:title="currentDialogTitle" 
				:mode="'input'" 
				:value="inputValue"
				placeholder="请输入内容"
				@confirm="confirmAddItem"
				@close="closeDialog">
			</uni-popup-dialog>
		</uni-popup>
		
		<!-- 添加渠道弹窗 -->
		<uni-popup ref="addChannelPopup" type="dialog">
			<view class="channel-dialog">
				<view class="dialog-title">添加渠道</view>
				<view class="dialog-content">
					<input type="text" class="dialog-input" v-model="newChannel.name" placeholder="渠道名称" />
					<input type="text" class="dialog-input" v-model="newChannel.link" placeholder="外部链接" />
				</view>
				<view class="dialog-buttons">
					<button class="dialog-btn cancel-btn" @tap="closeChannelDialog">取消</button>
					<button class="dialog-btn confirm-btn" @tap="confirmAddChannel">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import { productApi} from '../../api/index.js';
	import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
	import uniPopupDialog from '@/uni_modules/uni-popup/components/uni-popup-dialog/uni-popup-dialog.vue';
	import UniDatetimePicker from '@/uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue';
	
	export default {
		components: {
			uniPopup,
			uniPopupDialog,
			UniDatetimePicker
		},
		data() {
			return {
				categories: ['耳饰','项链','手链','戒指','胸针'],
				selectedCategory: "",
				warehouses: ['电商', '门店'],
				selectedWarehouse: "",
				// 珍珠颜色选项
				pearlColors: ['白色', '金色', '黑色', '灰色', '粉色', '其他'],
				selectedPearlColor: "",
				// 珍珠圆度选项
				pearlRoundness: ['正圆', '圆', '椭圆', '异形', '其他'],
				selectedPearlRoundness: "",
				// 珍珠净度选项
				pearlClarities: ['无暇', '微瑕', '螺纹', '其他'],
				selectedPearlClarity: "",
				// 珍珠材质选项
				pearlMaterials: ['海水珍珠', '淡水珍珠', '人造/贝珠', '其他', '无珍珠'],
				selectedPearlMaterial: "",
				// 金属材质选项
				metalMaterials: ['铜镀金', '银镀金', '925银', 'K金', '足金', '其他'],
				selectedMetalMaterial: "",
				// 售卖渠道选项
				channels: ['微信', '抖音', '淘宝', '京东', '小红书', '其他'],
				
				// 用于存放已经加载的规格选项
				selectedLengthList: [],
				selectedDiameterList: [],
				selectedPearlSizeList: [],
				selectedPearlColorList: [],
				
				product: {
					name: '',
					category: '',
					price: '',
					preview_image_url: '',
					warehouse: '电商', // 默认值
					date: '', // 新增日期字段
					
					// 新的扁平化属性结构
					length: '', // 单独的长度值
					diameter: '', // 单独的直径值
					pearlSize: '', // 单独的珍珠尺寸值
					pearlColor: '', // 单独的珍珠颜色值
					
					// 珍珠属性
					pearlMaterial: '',
					pearlRoundness: '',
					pearlClarity: '',
					
					// 配件属性
					metalMaterial: '',
					jadeSize: '',
					jadeMaterial: '',
					accessoryOthers: '',
					
					channel: [], // 渠道列表
					remark: ''
				},
				isLoading: false,
				isUploading: false,
				
				// 弹窗相关
				currentListType: '',
				currentDialogTitle: '',
				inputValue: '',
				newChannel: {
					name: '',
					link: ''
				}
			}
		},
		onLoad(options) {
			// 检查用户权限
			this.checkUserRole();
			
			if (options.id) {
				// 如果有ID，表示是编辑现有产品，从服务器获取产品信息
				this.getProductInfo(options.id);
			} else {
				// 如果没有ID，表示是创建新产品，所有选择项初始值为空
				this.selectedCategory = "";
				this.selectedWarehouse = ""; // 默认值
				this.selectedPearlMaterial = "";
				this.selectedPearlRoundness = "";
				this.selectedPearlClarity = "";
				this.selectedPearlColor = "";
				this.selectedMetalMaterial = "";
				// 产品基本信息也初始化为空
				this.product = {
					name: '',
					category: '',
					price: '',
					preview_image_url: '',
					warehouse: '', // 默认仓库
					date: '',
					pearlMaterial: '',
					pearlRoundness: '',
					pearlClarity: '',
					metalMaterial: '',
					jadeSize: '',
					jadeMaterial: '',
					accessoryOthers: '',
					channel: [],
					remark: ''
				};
			}
		},
		onReady() {
			// 检查组件是否正确加载
			console.log('页面已准备就绪，检查组件引用：');
			console.log('addItemPopup:', this.$refs.addItemPopup);
			console.log('addChannelPopup:', this.$refs.addChannelPopup);
			
			// 如果组件未加载，在控制台输出警告
			if (!this.$refs.addItemPopup || !this.$refs.addChannelPopup) {
				console.warn('警告：uni-popup组件未正确加载，将使用原生弹窗替代');
			}
		},
		methods: {
			// 检查用户角色并设置权限
			checkUserRole() {
				try {
					// 获取本地存储的用户信息
					const userInfo = uni.getStorageSync('userInfo');
					
					// 判断用户是否为admin或employee
					if (!(userInfo && (userInfo.role === 'admin' || userInfo.role === 'employee'))) {
						uni.showToast({
							title: '您没有权限访问此页面',
							icon: 'none',
							duration: 2000
						});
						
						// 延迟返回，让用户有时间看到提示
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				} catch (error) {
					console.error('获取用户角色失败', error);
					uni.showToast({
						title: '权限验证失败',
						icon: 'none',
						duration: 2000
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}
			},
			handleCategoryChange(e) {
				const index = e.detail.value;
				this.selectedCategory = this.categories[index];
				this.product.category = this.selectedCategory;
			},
			handleWarehouseChange(e) {
				const index = e.detail.value;
				this.selectedWarehouse = this.warehouses[index];
				this.product.warehouse = this.selectedWarehouse;
			},
			handleDateChange(e) {
				console.log('日期变更:', e);
				this.product.date = e;
				// 确保日期显示在控制台，便于调试
				console.log('更新后的日期值:', this.product.date);
			},
			// 珍珠材质选择
			handlePearlMaterialChange(e) {
				const index = e.detail.value;
				this.selectedPearlMaterial = this.pearlMaterials[index];
				this.product.pearlMaterial = this.selectedPearlMaterial;
			},
			// 珍珠圆度选择
			handlePearlRoundnessChange(e) {
				const index = e.detail.value;
				this.selectedPearlRoundness = this.pearlRoundness[index];
				this.product.pearlRoundness = this.selectedPearlRoundness;
			},
			// 珍珠净度选择
			handlePearlClarityChange(e) {
				const index = e.detail.value;
				this.selectedPearlClarity = this.pearlClarities[index];
				this.product.pearlClarity = this.selectedPearlClarity;
			},
			// 金属材质选择
			handleMetalMaterialChange(e) {
				const index = e.detail.value;
				this.selectedMetalMaterial = this.metalMaterials[index];
				this.product.metalMaterial = this.selectedMetalMaterial;
			},
			// 珍珠颜色选择
			handlePearlColorChange(e) {
				const index = e.detail.value;
				this.selectedPearlColor = this.pearlColors[index];
				this.product.pearlColor = this.selectedPearlColor;
			},
			async chooseImage() {
				// 如果已经在上传中，阻止重复操作
				if (this.isUploading) return;
				
				try {
					const res = await new Promise((resolve, reject) => {
						uni.chooseImage({
							count: 1,
							success: resolve,
							fail: reject
						});
					});
					
					// 显示上传中遮罩
					this.isUploading = true;

					console.log(res.tempFilePaths[0])
					
					// 获取原始文件后缀名
					const filePath = res.tempFilePaths[0];
					const fileExtension = filePath.substring(filePath.lastIndexOf('.'));
					
					// 上传图片到云存储
					wx.cloud.uploadFile({
						cloudPath: 'productsImage/' + new Date().getTime() + "_" + Math.floor(Math.random()*1000) + fileExtension,
						filePath: res.tempFilePaths[0], // 文件路径
						success: res => {
							// 获取文件ID并更新图片URL
							console.log('图片上传成功:', res.fileID);
							this.product.preview_image_url = res.fileID;
							
							// 上传成功提示
							uni.showToast({
								title: '图片上传成功',
								icon: 'success',
								duration: 2000
							});
						},
						fail: err => {
							// 上传失败处理
							console.error('图片上传失败:', err);
							uni.showToast({
								title: '图片上传失败',
								icon: 'none',
								duration: 2000
							});
						},
						complete: () => {
							// 无论成功失败，都需要关闭上传状态
							setTimeout(() => {
								this.isUploading = false;
							}, 500);
						}
					});
				} catch (error) {
					console.error('选择图片失败', error);
					this.isUploading = false;
					
					uni.showToast({
						title: '选择图片失败',
						icon: 'none',
						duration: 2000
					});
				}
			},
			
			// 列表项相关方法
			showAddItemDialog(listType) {
				this.currentListType = listType;
				
				// 设置对话框标题
				const titles = {
					'lengthList': '添加整体长度',
					'diameterList': '添加佩戴直径',
					'pearlSizeList': '添加珍珠尺寸',
					'pearlColorList': '添加珍珠颜色'
				};
				
				this.currentDialogTitle = titles[listType] || '添加项目';
				this.inputValue = '';
				
				// 特殊处理珍珠颜色，使用下拉选择而不是文本输入
				if (listType === 'pearlColorList') {
					// 过滤掉已经选择的颜色
					const availableColors = this.pearlColors.filter(color => 
						!this.selectedPearlColorList.includes(color)
					);
					
					if (availableColors.length === 0) {
						uni.showToast({
							title: '已添加所有可用颜色',
							icon: 'none'
						});
						return;
					}
					
					uni.showActionSheet({
						itemList: availableColors,
						success: (res) => {
							const selectedColor = availableColors[res.tapIndex];
							this.confirmAddItem(selectedColor);
						}
					});

					
				} else {
					// 其他类型使用文本输入
					uni.showModal({
						title: this.currentDialogTitle,
						editable: true,
						placeholderText: '请输入内容',
						success: (res) => {
							if (res.confirm && res.content) {
								this.confirmAddItem(res.content);
							}
						}
					});
				}
			},
			
			confirmAddItem(value) {
				if (!value.trim()) {
					uni.showToast({
						title: '内容不能为空',
						icon: 'none'
					});
					return;
				}
				
				// 获取当前操作的列表
				let targetList = [];
				switch (this.currentListType) {
					case 'lengthList':
						targetList = this.selectedLengthList;
						break;
					case 'diameterList':
						targetList = this.selectedDiameterList;
						break;
					case 'pearlSizeList':
						targetList = this.selectedPearlSizeList;
						break;
					case 'pearlColorList':
						targetList = this.selectedPearlColorList;
						break;
				}
				
				// 检查是否已存在相同的值（不区分大小写）
				const isDuplicate = targetList.some(item => 
					item.toLowerCase() === value.trim().toLowerCase()
				);
				
				if (isDuplicate) {
					uni.showToast({
						title: '该项目已存在',
						icon: 'none'
					});
					return;
				}
				
				// 不存在重复，添加到相应的列表中
				switch (this.currentListType) {
					case 'lengthList':
						this.selectedLengthList.push(value);
						break;
					case 'diameterList':
						this.selectedDiameterList.push(value);
						break;
					case 'pearlSizeList':
						this.selectedPearlSizeList.push(value);
						break;
					case 'pearlColorList':
						this.selectedPearlColorList.push(value);
						break;
				}
			},
			
			deleteItem(listType, index) {
				// 根据不同的列表类型，从相应的列表中删除项目
				switch (listType) {
					case 'lengthList':
						this.selectedLengthList.splice(index, 1);
						break;
					case 'diameterList':
						this.selectedDiameterList.splice(index, 1);
						break;
					case 'pearlSizeList':
						this.selectedPearlSizeList.splice(index, 1);
						break;
					case 'pearlColorList':
						this.selectedPearlColorList.splice(index, 1);
						break;
				}
			},
			
			closeDialog() {
				this.$refs.addItemPopup.close();
			},
			
			// 渠道相关方法
			showAddChannelDialog() {
				this.newChannel = { name: '', link: '' };
				
				// 使用选择器来选择渠道名称
				uni.showActionSheet({
					itemList: this.channels,
					success: (res) => {
						this.newChannel.name = this.channels[res.tapIndex];
						this.inputChannelLink();
					}
				});
			},
			
			// 分步输入渠道链接
			inputChannelLink() {
				uni.showModal({
					title: '渠道链接',
					editable: true,
					placeholderText: '请输入外部链接',
					success: (res) => {
						if (res.confirm && res.content) {
							this.newChannel.link = res.content;
							this.confirmAddChannel();
						}
					}
				});
			},
			
			confirmAddChannel() {
				if (!this.newChannel.name.trim() || !this.newChannel.link.trim()) {
					uni.showToast({
						title: '渠道名称和链接不能为空',
						icon: 'none'
					});
					return;
				}
				console.log(this.product)
				this.product.channel.push({...this.newChannel});
				this.closeChannelDialog();
			},
			
			deleteChannel(index) {
				this.product.channel.splice(index, 1);
			},
			
			closeChannelDialog() {
				this.$refs.addChannelPopup.close();
			},
			
			async getProductInfo(id) {
				try {
					uni.showLoading({ title: '加载中...' });
					this.isLoading = true;
					
					// 调用API获取商品详情
					const result = await productApi.getProductDetail(id);
					
					// 填充表单数据
					if (!result || !result.data) {
						throw new Error('获取商品数据失败');
					}
					
					const productData = result.data;
					
					// 将商品ID保存到产品对象中并填充相关属性
					this.product = {
						id: id,
						name: productData.name || '',
						category: productData.category || '',
						preview_image_url: productData.preview_image_url || '',
						warehouse: productData.warehouse || '电商',
						date: productData.date || '',
						
						// 珍珠属性
						pearlMaterial: productData.pearlMaterial || '',
						pearlRoundness: productData.pearlRoundness || '',
						pearlClarity: productData.pearlClarity || '',
						
						// 配件属性
						metalMaterial: productData.metalMaterial || '',
						jadeSize: productData.jadeSize || '',
						jadeMaterial: productData.jadeMaterial || '',
						accessoryOthers: productData.accessoryOthers || '',
						
						channel: productData.channel || [], // 渠道列表
						remark: productData.remark || '',
						skus: productData.skus || []
					};
					
					// 打印日期值，便于调试
					console.log('获取到的日期值:', this.product.date);
					
					// 确保日期格式符合要求 (yyyy-MM-dd)
					if (this.product.date && typeof this.product.date === 'string') {
						// 尝试标准化日期格式
						try {
							// 如果已经是标准格式，不需要任何处理
							if (!/^\d{4}-\d{2}-\d{2}$/.test(this.product.date)) {
								// 尝试转换为标准格式
								const date = new Date(this.product.date);
								if (!isNaN(date.getTime())) {
									const year = date.getFullYear();
									const month = String(date.getMonth() + 1).padStart(2, '0');
									const day = String(date.getDate()).padStart(2, '0');
									this.product.date = `${year}-${month}-${day}`;
								}
							}
						} catch (error) {
							console.error('日期格式转换错误:', error);
						}
					}
					
					console.log('标准化后的日期值:', this.product.date);
					
					// 直接设置选择的值，而不是索引
					this.selectedCategory = this.product.category || '';
					this.selectedWarehouse = this.product.warehouse || '';
					this.selectedPearlMaterial = this.product.pearlMaterial || '';
					this.selectedPearlRoundness = this.product.pearlRoundness || '';
					this.selectedPearlClarity = this.product.pearlClarity || '';
					this.selectedPearlColor = this.product.pearlColor || '';
					this.selectedMetalMaterial = this.product.metalMaterial || '';
					
					// 清空并初始化规格列表
					this.selectedLengthList = [];
					this.selectedDiameterList = [];
					this.selectedPearlSizeList = [];
					this.selectedPearlColorList = [];
					
					// 从SKU数据中提取规格值
					// 根据skus来初始化规格列表，skus是一个list，每一项是一个dict
					if (productData.skus && productData.skus.length > 0) {
						productData.skus.forEach(sku => {
							// 长度
							if (sku.length && !this.selectedLengthList.includes(sku.length)) {
								this.selectedLengthList.push(sku.length);
							}
							// 直径
							if (sku.diameter && !this.selectedDiameterList.includes(sku.diameter)) {
								this.selectedDiameterList.push(sku.diameter);
							}
							// 珍珠尺寸
							if (sku.pearlSize && !this.selectedPearlSizeList.includes(sku.pearlSize)) {
								this.selectedPearlSizeList.push(sku.pearlSize);
							}
							// 珍珠颜色
							if (sku.pearlColor && !this.selectedPearlColorList.includes(sku.pearlColor)) {
								this.selectedPearlColorList.push(sku.pearlColor);
							}
						});
					}
					
					uni.hideLoading();
					this.isLoading = false;
					
					console.log('商品数据加载成功', this.product);
				} catch (error) {
					console.error('获取商品信息失败', error);
					uni.hideLoading();
					this.isLoading = false;
					
					uni.showToast({
						title: '获取商品信息失败',
						icon: 'none'
					});
				}
			},
			
			validateForm() {
				// 表单验证
				if (!this.product.name) {
					uni.showToast({
						title: '请输入商品名称',
						icon: 'none'
					});
					return false;
				}
				if (!this.product.category) {
					uni.showToast({
						title: '请选择商品类别',
						icon: 'none'
					});
					return false;
				}
				
				// 验证预览图
				if (!this.product.preview_image_url) {
					uni.showToast({
						title: '请上传商品预览图',
						icon: 'none'
					});
					return false;
				}
				
				// 验证日期
				if (!this.product.date) {
					uni.showToast({
						title: '请选择时间',
						icon: 'none'
					});
					return false;
				}
				
				return true;
			},
			goToSkuPage() {
				// 如果表单未通过验证，不允许跳转
				if (!this.validateForm()) return;
				
				// 先保存基本信息
				uni.showLoading({ title: '准备SKU数据...' });
				
				// 根据模型填充传递数据
				const productData = {
					id: this.product.id,
					name: this.product.name,
					category: this.product.category,
					preview_image_url: this.product.preview_image_url,
					warehouse: this.product.warehouse,
					date: this.product.date,
					
					// 珍珠属性
					pearlMaterial: this.product.pearlMaterial,
					pearlRoundness: this.product.pearlRoundness,
					pearlClarity: this.product.pearlClarity,
					
					// 配件属性
					metalMaterial: this.product.metalMaterial,
					jadeSize: this.product.jadeSize,
					jadeMaterial: this.product.jadeMaterial,
					accessoryOthers: this.product.accessoryOthers,
					
					// 备注信息
					remark: this.product.remark,
					
					// 渠道信息
					channel: this.product.channel|| [],
					
					// 传递已有SKU数据，以便在生成新SKU时保留旧SKU信息
					skus: this.product.skus || []
				};
				console.log('准备传递的数据:', productData);
				
				const selectedInfo = {
					// 商品规格相关
					lengthList: this.selectedLengthList,
					diameterList: this.selectedDiameterList,
					
					// 珍珠相关
					pearlSizeList: this.selectedPearlSizeList,
					pearlColorList: this.selectedPearlColorList
				};

				const data = {
					productData,
					selectedInfo
				};
				
				// 临时保存到本地
				uni.setStorageSync('temp_product_data', JSON.stringify(data));
				
				uni.hideLoading();
				
				// 将产品数据传递到SKU页面
				uni.navigateTo({
					url: `/pages/product/sku?productData=${encodeURIComponent(JSON.stringify(data))}`
				});
			},
			goBack() {
				// 实现返回逻辑
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 120rpx;
	}
	
	.form-section {
		background-color: #fff;
		padding: 20rpx;
	}
	
	.section-title {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		margin: 30rpx 0 20rpx;
	}
	
	.top-layout {
		display: flex;
		margin-bottom: 20rpx;
		align-items: flex-start; /* 顶部对齐 */
	}
	
	.image-container {
		width: 200rpx;
		height: 240rpx; /* 增加高度以容纳标签 */
		margin-right: 20rpx;
		display: flex;
		flex-direction: column;
	}
	
	.image-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.info-container {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
	}
	
	.form-row {
		display: flex;
		justify-content: space-between;
		gap: 10rpx;
	}
	
	.half-width {
		width: calc(50% - 5rpx); /* 减去一半的间距 */
	}
	
	.form-item {
		margin-bottom: 1rpx;
	}
	
	/* 水平布局样式 */
	.horizontal {
		display: flex;
		align-items: center;
	}
	
	
	.label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}
	
	input {
		flex: 1;
		height: 70rpx;
		background-color: #ffffff;
		
		border-radius: 8rpx;
		padding: 0 10rpx;
		font-size: 28rpx;
	}
	
	.picker {
		flex: 1;
		height: 70rpx;
		line-height: 70rpx;
		background-color: #ffffff;
		border-radius: 8rpx;
		padding: 0 10rpx;
		font-size: 28rpx;
	}
	
	.image-upload {
		width: 200rpx;
		height: 200rpx; /* 确保是正方形 */
		background-color: #ffffff;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.preview-image {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
		object-fit: cover; /* 确保图片填充并保持比例 */
	}
	
	.upload-placeholder {
		font-size: 60rpx;
		color: #333;
	}
	
	/* 列表相关样式 */
	.list-container {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}
	
	.list-item {
		background-color: #ffffff;
		border-radius: 8rpx;
		padding: 16rpx 24rpx;
		display: flex;
		align-items: center;
	}
	
	.item-text {
		font-size: 28rpx;
		color: #333;
		margin-right: 16rpx;
	}
	
	.delete-btn {
		color: #333;
		font-size: 40rpx;
		line-height: 1;
		width: 40rpx;
		height: 40rpx;
		text-align: center;
	}
	
	.add-item-btn {
		width: 80rpx;
		height: 80rpx;
		background-color: #ffffff;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 40rpx;
		color: #333;
	}
	
	/* 渠道相关样式 */
	.channel-list {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}
	
	.channel-item {
		background-color: #ffffff;
		border-radius: 8rpx;
		padding: 16rpx 24rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.channel-content {
		flex: 1;
	}
	
	.channel-name {
		font-size: 28rpx;
		color: #333;
		display: block;
		margin-bottom: 8rpx;
	}
	
	.channel-link {
		font-size: 24rpx;
		color: #F3B250;
		display: block;
	}
	
	.channel-dialog {
		padding: 30rpx;
		background-color: #fff;
		border-radius: 16rpx;
	}
	
	.dialog-title {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30rpx;
	}
	
	.dialog-content {
		margin-bottom: 30rpx;
	}
	
	.dialog-input {
		width: 100%;
		height: 80rpx;
		background-color: #ffffff;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}
	
	.dialog-buttons {
		display: flex;
		justify-content: space-between;
	}
	
	.dialog-btn {
		width: 45%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 8rpx;
	}
	
	.cancel-btn {
		background-color: #ffffff;
		color: #333;
	}
	
	.confirm-btn {
		background-color: #F3B250;
		color: #fff;
	}
	
	.remark-input {
		width: 100%;
		height: 200rpx;
		background-color: #ffffff;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 28rpx;
	}
	
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 90rpx;
		background-color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.bottom-divider {
		height: 1rpx;
		background-color: #eee;
		width: 100%;
	}
	
	.bottom-btn-container {
		display: flex;
		height: 90rpx;
		background-color: #fff;
		align-items: center;
		justify-content: center;
		padding: 0 10rpx;
	}
	
	.back-btn {
		
		flex: 0 0 auto;
		width: 200rpx;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		width: 200rpx;
		background-color: #fff;
		color: #282828;
		border-radius: 0rpx;
		border: 4rpx solid #dcc8a5;
		margin: 0 15rpx;
		font-size: 28rpx;
		font-family: Regular;
		padding: 0;
	}
	
	.back-btn::after {
		border: none;
	}
	
	.next-btn {
		flex: 0 0 auto;
		width: 200rpx;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		background-color: #282828;
		color: #fff;
		border-radius: 0rpx;
		border: 4rpx solid #dcc8a5;
		margin: 0 15rpx;
		font-size: 28rpx;
		font-family: Regular;
		padding: 0;
	}
	
	.next-btn::after {
		border: none;
	}
	
	/* 全屏加载遮罩样式 */
	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.loading-content {
		background-color: rgba(0, 0, 0, 0.7);
		border-radius: 16rpx;
		padding: 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.loading-spinner {
		width: 80rpx;
		height: 80rpx;
		border: 6rpx solid #f3f3f3;
		border-top: 6rpx solid #F3B250;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}
	
	.loading-text {
		color: #ffffff;
		font-size: 28rpx;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
	
	/* 带单位的输入框样式 */
	.input-with-unit {
		position: relative;
		display: flex;
		align-items: center;
		flex: 1;
	}
	
	.input-with-unit input {
		flex: 1;
		padding-right: 35rpx; /* 为单位腾出空间 */
		background-color: #ffffff;
	}
	
	.unit-label {
		position: absolute;
		right: 10rpx;
		color: #333;
		font-size: 24rpx;
	}
	
	/* 统一宽度的输入框 */
	.full-width-input {
		flex: 1;
		width: 100%;
	}
	
	.full-width-input .picker {
		height: 70rpx;
		line-height: 70rpx;
		background-color: #ffffff;
		border-radius: 8rpx;
		padding: 0 10rpx;
		font-size: 28rpx;
	}
	
	/* 日历选择器样式 */
	.calendar-picker {
		flex: 1;
		height: 70rpx;
		border-radius: 8rpx;
	}
	
	/* 必填标记样式 */
	.required-mark {
		color: #F3B250;
		font-size: 24rpx;
		margin-left: 4rpx;
	}
</style> 